<template>
  <div>
    <avue-crud
      :data="data.data"
      :option="option"
      @row-save="create"
      @row-update="update"
      @row-del="remove"
    ></avue-crud>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';

@Component({})
export default class ResourceList extends Vue {
  @Prop(String) resource !: string;
  data = {};
  option = {};

  async fetch() {
    const { data } = await this.$http.get(`${this.resource}`);
    this.data = data;
  }

  async fetchOption() {
    const { data } = await this.$http.get(`${this.resource}/option`);
    this.option = data;
  }

  async create(row, done, loading) {
    await this.$http.post(`${this.resource}`, row);
    this.$message.success('创建成功');
    this.fetch();
    done();
  }

  async update(row, index, done, loading) {
    const data = JSON.parse(JSON.stringify(row));
    delete data.$index;
    await this.$http.put(`${this.resource}/${data._id}`, data);
    this.$message.success('创建成功');
    this.fetch();
    done();
  }

  async remove(row, index) {
    await this.$http.delete(`${this.resource}/${row._id}`);
    this.fetch();
    this.$message.success('成功');
  }
  created() {
    this.fetch();
    this.fetchOption();
  }
}
</script>